﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace GlobalizationTools.UI
{
    public class MenuButton : MenuItem
    {
        static MenuButton()
        {
            ButtonBase.CommandProperty.AddOwner(typeof(MenuButton),
                new FrameworkPropertyMetadata(null,
                    new PropertyChangedCallback(MenuButton.OnCommandChanged)));

            MenuItem.IconProperty.OverrideMetadata(typeof(MenuButton),
                new FrameworkPropertyMetadata(null,
                    new CoerceValueCallback(MenuButton.CoerceIcon)));

        }

        private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((MenuButton)d).OnCommandChanged((ICommand)e.OldValue, (ICommand)e.NewValue);
        }

        private void OnCommandChanged(ICommand oldCommand, ICommand newCommand)
        {
            base.CoerceValue(MenuItem.IconProperty);
        }

        private static object CoerceIcon(DependencyObject d, object value)
        {
            MenuButton container = (MenuButton)d;
            if (value == null)
            {
                RoutedUICommandEx commandEx = container.Command as RoutedUICommandEx;
                if (commandEx != null)
                {
                    if (commandEx.Image != null)
                    {
                        AutoGreyableImage img = new AutoGreyableImage();
                        img.Source = commandEx.Image;
                        return img;
                    }
                }
            }
            return value;
        }


    }
}
